package com.asiainfo.indb.control;

import com.asiainfo.indb.control.db.FileLineInDb;
import com.asiainfo.indb.control.db.pool.DbPoolFactory;
import com.asiainfo.indb.model.InDbGather;

/**
 * @author zym
 * @date 2019-10-21 11:23
 */
public class JavaInDbTask implements Runnable {

    private FileCutter cutter;

    private LogService log;

    private InDbGather gather;

    public JavaInDbTask(FileCutter cutter, LogService log, InDbGather gather) {
        this.log = log;
        this.cutter = cutter;
        this.gather = gather;
    }

    @Override
    public void run() {
        FileLineInDb fileLineInDb = null;
        try (FileCutter.FixedFileReader reader = cutter.nextRandomAccessor()) {
            if (reader != null) {
                // TODO 当前仅实现了oracle下的批量入库模式，如果采用其它数据库需要自行实现对应数据库方言
                fileLineInDb = DbPoolFactory.getPool(gather).getDialect().getFileLineInDb(gather, log);
                if (fileLineInDb != null) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        // 开始入库
                        fileLineInDb.inDb(line);
                    }
                }
            }
        } catch (Exception e) {
            log.report(Thread.currentThread().getName() + "线程入库异常：" + e.getMessage());
        } finally {
            log.done();

            // 停止入库
            if (fileLineInDb != null) {
                fileLineInDb.endInDb();
            }
        }
    }
}
